<!-- 表格组件 -->
<template>
  <div ref="tablBox" class="tablBox">
    <el-table
      ref="table"
      :data="tableData"
      style="width: 100%"
      stripe
      :show-header="true"
      :border="border"
      :max-height="height"
      :cell-style="cellStyle"
      :header-cell-style="headerCellStyle"
      :span-method="spanMethod"
      :show-summary="showSummary"
      :summary-method="summaryMethod"
      :row-style="rowStyle"
      @cell-click="cellClick"
      @selection-change="handleSelectionChange"
      @select="handleSelection"
      @header-click="headerClick"
      @sort-change="handerSortChange"
      v-bind="$attrs"
    >
    <el-table-column
    v-if="showSelection"
    type="selection"
    width="55"
    align="center"
  ></el-table-column>
      <el-table-column label="序号" type="index" align="center" width="55">
        <template slot-scope="scope">{{
          scope.$index + (page.page - 1) * page.size + 1
        }}</template>
      </el-table-column>
      <el-table-column
        v-for="(item, index) in tableColumns"
        v-if="item.show && item.label !== '操作' && !item.fixed"
        :key="item.id"
        :prop="item.column"
        :label="item.label + (item.specialLabel ? item.specialLabel : '')"
        :min-width="item.width"
        :fixed="item.fixed"
        :align="item.align"
        :show-overflow-tooltip="true"
        :sortable="item.sortable"
      >
        <template v-if="item.headerFilter" slot="header">
          <span>{{
            item.label + (item.specialLabel ? item.specialLabel : "")
          }}</span>
          <el-popover
            @show="headerPopoverShow(item, index)"
            @hide="headerPopoverHide(item, index)"
            :ref="'filterPanel' + index"
            placement="bottom"
            visible-arrow="false"
            trigger="click"
          >
            <i
              slot="reference"
              style="margin-left: 5px"
              @click.stop
              class="el-icon-arrow-down"
            ></i>
            <!-- 分为码值下拉框，搜索框，时间和按照表格数据筛选四种格式 -->

            <!-- 码值 -->
            <div v-if="item.filterType === 'select'">
              <div class="header-table">
                <el-table
                  :ref="'headerTable' + item.label"
                  @selection-change="headerTableSelection"
                  @row-click="headerTableClick"
                  :data="item.headerFilterList"
                  max-height="250"
                  :border="false"
                >
                  <el-table-column width="30" align="center" type="selection" />
                  <el-table-column
                    align="left"
                    prop="value"
                    label="全选"
                    header-align="left"
                  ></el-table-column>
                </el-table>
              </div>
            </div>
            <!-- 输入框 -->
            <div v-if="item.filterType === 'input'">
              <div class="header-table">
                <el-input
                  v-model="item.filterValue"
                  placeholder="请输入"
                  @input="change($event, item)"
                ></el-input>
              </div>
            </div>
            <!-- 时间，年月日 -->
            <div v-if="item.filterType === 'daterange'">
              <div class="header-table">
                <el-date-picker
                  v-model="item.filterValue"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyyMMdd"
                  class="rangedate"
                >
                </el-date-picker>
              </div>
            </div>
            <div v-if="item.filterType === 'date'">
              <div class="header-table">
                <el-date-picker
                  v-model="item.filterValue"
                  type="date"
                  placeholder="选择记录日期"
                  value-format="yyyyMMdd"
                >
                </el-date-picker>
              </div>
            </div>
            <!-- 根据表格数据来 -->
            <div v-if="!item.filterType">
              <div class="search-input">
                <input
                  v-model="item.search"
                  @input="headerInput(item, index)"
                  :placeholder="item.label"
                />
              </div>
              <div class="header-table">
                <el-table
                  :ref="'headerTable' + item.label"
                  @selection-change="headerTableSelection"
                  @row-click="headerTableClick"
                  :data="item.filters"
                  max-height="250"
                  :border="false"
                >
                  <el-table-column width="30" align="center" type="selection" />
                  <el-table-column
                    align="left"
                    prop="value"
                    :min-width="item.filterWidth || 200"
                    label="全选"
                    header-align="left"
                  ></el-table-column>
                </el-table>
              </div>
            </div>

            <div class="headerTable-bottom">
              <el-button
                type="text"
                size="small"
                @click="headerFilter(item, index)"
                >筛选</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="headeronReset(item, index)"
                >重置</el-button
              >
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        v-for="(item, index) in tableColumns"
        v-if="item.show && item.label !== '操作' && item.fixed"
        :key="item.id"
        :prop="item.column"
        :label="item.label + (item.specialLabel ? item.specialLabel : '')"
        :min-width="item.width"
        :fixed="item.fixed"
        :align="item.align"
        :show-overflow-tooltip="true"
        :sortable="item.sortable"
      >
        <template slot-scope="scope">
          <span>{{ scope.row[item.column] }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-for="(item, index) in tableColumns"
        v-if="item.show && item.label === '操作'"
        :key="item.id"
        :label="item.label"
        :min-width="item.width"
        :fixed="item.fixed"
        :align="item.align"
      >
        <template slot-scope="scope">
          <el-button
            v-for="(btnItem, btnIndex) in item.btns"
            :key="'operate' + btnIndex"
            size="mini"
            @click="handleOperate(btnItem, item, scope.row)"
            type="text"
            >{{ btnItem.label }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { setTimeout, clearTimeout } from "timers";
import moment from "moment";
// 这是12.06封装的组件 之前的组件 头部筛选框
// 使用$set 和 = 都不会驱动视图的变化
// 这个组件 是直接使用之前的头部筛选框代码 还需后期优化 替换$set
export default {
  components: {
    // ExportImgPanel
  },
  props: {
    page: {
      default: () => {},
    },
    tableData: {
      type: Array,
      default: () => {},
    },
    tableColumns: {
      type: Array,
      default: () => {},
    },
    border: {
      type: Boolean,
      default: false,
    },
    height: {
      type: Number,
      default: null,
    },
    showHandle: {
      type: Boolean,
      default: false,
    },
    showIndex: {
      type: Boolean,
      default: false,
    },
    showSummary: {
      type: Boolean,
      default: false,
    },
    showSelection: {
      type: Boolean,
      default: false,
    },
    spanMethod: {
      type: Function,
      default: () => {},
    },
    summaryMethod: {
      type: Function,
      default: () => {},
    },
    rowStyle: {
      type: Function,
      default: () => {},
    },
    /* editRowIndexArr: {
      type: Array,
      default: () => {}
    },
    isRowEdit: {
      type: Boolean,
      default: false
    }, */
    isEdit: {
      type: Boolean,
      default: true,
    },
    cellStyle: {
      type: Function,
      default: () => {},
    },
    
    // headerCellStyle: {
    //   type: Function,
    //   default: () => {}
    // },
    renderHeader: {
      type: Function,
      default: () => {},
    },
    tableTitle: {
      type: String,
      default: "",
    },
    checkConfig: {
      type: Array,
      default: () => {},
    },
    tableDataFilter: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      showTable: false,
      infoTableData: [],
      rowHeight: 35,
      tableInfoData: [],
      // search: "",
      // filterPanelVisible: false,
      // headerTableData: [],
      // sortOrder: "none",
      timer: null,
      filtersData: [],
      headerSelection: [],
      tableDataCopy: [],
      isHeaderSearch: false,
      headerFilterLabel: [],
      tableDataIndex: 0, // 是否第一次进入
      // pageIndex: Math.random()
      //   maxheight: 0,
      // 筛选
    };
  },
  computed: {},
  watch: {
    tableData: {
      handler: function (newValue, oldValue) {
        // 筛选之后 点击字段查看明细 会触发tableData的监听事件
        // 所以不能在 这里清空 tableDataCopy 和isHeaderSearch
        // 增加page的监听事件 如果更换新的页面 就重新渲染
        // this.isHeaderSearch = false;
        // this.tableDataIndex++;
        // this.getFilter(newValue);
        // this.tableDataCopy = [];
        // console.log(this.tableColumns, "this.tableColumns2222");
      },
      deep: true,
      immediate: true,
    },
    page: {
      handler: function (newValue, oldValue) {
        this.isHeaderSearch = false;
        this.tableDataCopy = [];
        this.headerFilterLabel = [];
        // this.getFilter();
      },
      deep: true,
      immediate: true,
    },
    tableDataFilter: {
      handler: function (newValue, oldValue) {
        this.getFilter(newValue);
      },
      deep: true,
      immediate: true,
    },
  },
  activated() {},
  mounted() {
    // this.fetchdata();
    // this.$nextTick(() => {
    //   this.$refs.basetable.doLayout(); //解决表格错位
    // })
    // this.$refs.scroll.$el.style.height =
    //   this.$refs.tablBox.clientHeight - 180 + "px";
    // 监听滚动条事件
    // this.handleScroll();
  },
  methods: {
    // 操作列
    handleOperate(btnItem, item, row) {
      console.log("操作列", btnItem, item, row);
      this.$emit(btnItem.fun, item, row);
    },
    getFilter(newValue) {
      // if (this.tableDataIndex == 2) {
      this.tableColumns.forEach((item, index) => {
        // item.filters1 = null;
        // item.headerTableSearch = true;
        // item.id = index;
        // item.sortOrder = "none";
        // item.filterPanel = false;
        if (!item.fixed && !item.isFilterTable) {
          item.id = Math.random();
          item.filters = [];
          const arr = [];
          const num = [];
          newValue.forEach((item1, index1) => {
            item1.id = index1;
            if (item1[item.column]) {
              num.push(item1[item.column].length * 14);
            }
            arr.push(item1[item.column]);
          });
          // console.log(Math.max(...num), "num");
          // console.log(Array.from(new Set(arr)), "Array.from(new Set(arr))");
          let filterHeaderData = [];
          if (item.label == "时间") {
            filterHeaderData = Array.from(new Set(arr)).sort(function (a, b) {
              if (new Date(a) && new Date(b)) {
                const x = new Date(a);
                const y = new Date(b);
                return x < y ? -1 : x > y ? 1 : 0;
              } else {
                return;
              }
            });
          } else {
            filterHeaderData = Array.from(new Set(arr)).sort();
          }
          filterHeaderData.forEach((item2) => {
            // console.log(item2, "item2");
            if (item2) {
              item.filters.push({
                text: item2,
                value: item2,
                id: item.label,
                // width: item2.length * 14
              });
            }
          });
          item.filterWidth = Math.max(...num);
        }
        // console.log("item.filters", item.filters);
      });
    },
    filternumMethod({ value, row, column }) {
      return parseInt(row.num) > value;
    },
    deleteHandle(row, rowIndex) {
      this.$emit("deleteHandle", { row, rowIndex });
    },
    handleSelectionChange(rows) {
      // 用一个变量来存放被选中的index
      const selectionItemIndexes = [];
      rows.forEach((item) => {
        selectionItemIndexes.push(item.index);
      });
      this.$emit("handleSelectionChange", { rows, selectionItemIndexes });
    },
    // 排序
    handerSortChange({ column, prop, order }) {
      this.$emit("handerSortChange", { column, prop, order });
    },
    /* tableRowClassName(row) {
      // 设置row对象的index
      // row.row.index = row.rowIndex
      // console.log(row)
    }, */
    //  文本框获得焦点事件
    inputFocus() {
      this.$emit("inputFocus");
    },
    handleSelection(selection, row) {
      this.$emit("handleSelection", { selection, row });
    },
    keyDown(e) {},
    headerClick(column, event) {
      // console.log("headerClick");
      //   this.$emit('headerClick',column)
    },
    popoverHide(scope) {
      // console.log("关闭popover");
      // console.log(row, "row");
      const refStr = `popover-${scope.column.property}-${scope.row.id}`;
      // if (scope.row.visible) {
      this.$refs[refStr][0].doClose();
      // scope.row.visible = false;
      // this.$set(scope.row, "visible", false);
      // }
      // console.log(scope, "scope");
    },
    cellClick(row, column, cell, e) {
      // 点击列表展开详情
      // 没有详情的，直接return
      if (this.tableTitle == "发行业务处理") {
        return;
      } else {
        const _this = this;
        // this.$emit("tableInfo", { _this, row, column, cell, e });
        return;
      }
    },
    saveTwo(num) {
      const str = num + "";
      if (str.indexOf(".") == -1) {
        return str;
      } else {
        return str.substr(0, str.indexOf(".") + 3);
      }
    },
    formatMoney(s, q) {
      var res = s.toString().replace(/\d+/, function (n) {
        // 先提取整数部分
        return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) {
          return $1 + ",";
        });
      });
      return this.saveTwo(res);
    },
    filterHandler(value, row, column) {
      const property = column["property"];
      return row[property] === value;
    },
    headerTableClick(row, column, event) {
      const tableRef = "headerTable" + row.id;
      if (this.$refs[tableRef].length != 0) {
        this.$refs[tableRef][0].toggleRowSelection(row);
      } else {
        this.$refs[tableRef].toggleRowSelection(row);
      }
    },
    headerTableSelection(selection) {
      if (selection.length == 0) {
        this.removeArr(this.headerSelection);
      } else {
        this.removeArr(this.headerSelection);
        selection.forEach((item, index) => {
          this.headerSelection.splice(index, 1, item);
        });
      }
    },
    headerCellStyle(row, column, rowIndex, columnIndex) {
      if (this.headerFilterLabel.includes(row.column.label)) {
        return {
          color: "#409eff",
        };
      } else {
        return {
          color: "#fff",
        };
      }
    },
    headerFilter(item, index) {
      const selection = this.headerSelection.map((item1) => {
        return item1.value;
      });
      const popoverRef = "filterPanel" + index;
      const obj = {
        popoverRef: popoverRef,
        selection: selection,
        column: item.column,
      };
      this.$emit("filterTable", obj);
      // 关闭弹框
      if (this.$refs[popoverRef]?.length > 0) {
        this.$refs[popoverRef].forEach((item) => {
          item.doClose();
        });
        this.$parent.getData();
      } else {
        this.$refs[popoverRef].doClose();
      }
    },
    headeronReset(item, index) {
      this.tableDataIndex = 1;
      const popoverRef = "filterPanel" + index;
      if (this.$refs[popoverRef]?.length > 0) {
        this.$refs[popoverRef].forEach((item) => {
          item.doClose();
        });
        // this.tableDataCopy = [];
        // this.headerSelection = [];
        // this.headerFilterLabel = [];
        // this.isHeaderSearch = false;
        this.tableColumns.forEach((item) => {
          item.isFilterTable = false;
        });
        this.$parent.getData();
      } else {
        this.$refs[popoverRef].doClose();
      }
    },
    headerInput(item, index) {
      clearTimeout(this.timer);
      const noSet = [];
      const yeseSet = [];
      if (true) {
        this.headerSelection = [];
        this.tableColumns.forEach((tabCol) => {
          if (tabCol.column == item.column) {
            this.tableData.forEach((item1) => {
              noSet.push(item1[tabCol.column]);
            });
            Array.from(new Set(noSet)).forEach((item2) => {
              if (item2) {
                yeseSet.push({
                  text: item2,
                  value: item2,
                });
              }
            });
          }
        });
        // 因为$set不能驱动视图层变化 所以循环使用splice
        yeseSet.forEach((yset, yindex) => {
          item.filters.splice(yindex, 1, yset);
        });
        // return;
      }
      const arr = [];
      this.timer = setTimeout(() => {
        item.filters.forEach((item1) => {
          const str = item1.value;
          if (str.indexOf(item.search) != -1) {
            arr.push(item1);
          }
        });
        if (item.filters.length != 0) {
          this.removeArr(item.filters);
        }
        arr.forEach((ar, arIndex) => {
          item.filters.splice(arIndex, 1, ar);
        });
      }, 500);
    },
    removeArr(arr) {
      // 因为赋值为空 或 $set设置为空 都不能驱动视图层变化 所以使用splice删除数组
      for (var i = 0; i < arr.length; i++) {
        arr.splice(i, 1);
        if (arr.length != 0) this.removeArr(arr);
      }
    },
    headerPopoverShow(column, i) {
      console.log("筛选弹框打开", column, i);
      // 关闭其他筛选弹框
      this.tableColumns.forEach((element, index) => {
        if (index !== i) {
          const popoverRef = "filterPanel" + index;
          if (this.$refs[popoverRef]?.length > 0) {
            this.$refs[popoverRef].forEach((item, index) => {
              item.doClose();
            });
          }
          if (this.$refs[popoverRef]?.length === 0) {
            this.$refs[popoverRef].doClose();
          }
        }
      });
    },
    headerPopoverHide(column, i) {
      console.log("筛选弹框关闭");
      this.tableColumns.forEach((item) => {
        // item.id = Math.random();
        // item.filters1 = null;
        item.search = "";
      });
    },
    //解决输入框无法输入
    change(value, item) {
      // this.$forceUpdate();
      item.filterValue = value;
    },
  },
};
</script>

<style lang="scss" scoped></style>
